package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.lock.domain.SysSetting;
import com.ruoyi.lock.service.ISysSettingService;
import com.ruoyi.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ISysSettingService sysSettingService;
    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysSetting sysSetting = sysSettingService.selectSysSettingByDeptId(user.getDeptId());

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        if(sysSetting!=null){
            ajax.put("sysSetting", "true");
        }else{
            ajax.put("sysSetting", "false");
        }
        ajax.put("setting", sysSetting);


        return ajax;
    }
    /**
     * WebSocket登录方法
     * 通过userId和WebSocket连接ID进行登录，成功后通过WebSocket发送登录信息给前端
     *
     * @param requestData 包含userId和wsId的请求数据
     * @return 结果
     */
    @Anonymous
    @PostMapping("/wsLogin")
    public AjaxResult wsLogin(@RequestBody Map<String, String> requestData)
    {
        try {
            String userId = requestData.get("userId");
            String wsId = requestData.get("wsId");

            if (StringUtils.isEmpty(userId)) {
                return AjaxResult.error("用户ID不能为空");
            }

            if (StringUtils.isEmpty(wsId)) {
                return AjaxResult.error("WebSocket连接ID不能为空");
            }


            // 调用登录服务进行WebSocket登录
            Map<String, Object> loginResult = loginService.wsLogin(userId, wsId);

            if (loginResult != null && (Boolean) loginResult.get("success")) {

                // 模仿账号密码登录的返回格式
                AjaxResult ajax = AjaxResult.success();

                // 直接从loginResult中获取token
                String token = (String) loginResult.get("token");

                if (token != null) {
                    ajax.put(Constants.TOKEN, token);
                } else {
                    return AjaxResult.error("登录成功但未获取到token");
                }

                return ajax;
            } else {
                String errorMsg = (String) loginResult.get("message");
                return AjaxResult.error(errorMsg != null ? errorMsg : "登录失败");
            }

        } catch (Exception e) {
            return AjaxResult.error("登录过程中发生异常：" + e.getMessage());
        }
    }

    /**
     * 临时秘钥登录方法
     * 通过临时秘钥进行登录
     * 
     * @param requestData 包含tempSecret的请求数据
     * @return 结果
     */
    @Anonymous
    @PostMapping("/tempSecretLogin")
    public AjaxResult tempSecretLogin(@RequestBody Map<String, String> requestData)
    {
        try {
            String tempSecret = requestData.get("tempSecret");
            
            if (StringUtils.isEmpty(tempSecret)) {
                return AjaxResult.error("临时秘钥不能为空");
            }

            // 调用登录服务进行临时秘钥登录
            String token = loginService.loginByTempSecret(tempSecret);
            
            // 返回token
            AjaxResult ajax = AjaxResult.success("登录成功");
            ajax.put(Constants.TOKEN, token);
            return ajax;
            
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
